import { defineStore } from 'pinia'
import { login } from '@/api/loginApi'
import logger from '@/utils/logger'
import { useMenuStore } from './menu'
export const useUserStore = defineStore('user', {
  state: () => ({
    token: '',
    nickname: '',
    profilePicture: null,
    category: null,
    dealerId: '',
    dealer: '',
    adminId: '',
    hasLogin: false,
  }),

  actions: {
    /**
     * 用户登录
     * @param {Object} loginParams - 登录参数
     * @returns {Promise} 登录结果
     */
    async fetchUserLogin(loginParams) {
      try {
        const res = await login(loginParams)
        if (res.success && res.code === 200) {
          const { token, nickname, profilePicture, category, dealerId, dealer, adminId } = res.data
          // 直接使用后端返回的字段，保持一致性
          this.setUserInfo({
            token,
            nickname,
            profilePicture,
            category,
            dealerId,
            dealer,
            adminId, // 直接使用adminId，不做映射
          })
          return res
        }
        return res
      } catch (error) {
        logger.error('登录失败:', error)
        return { success: false, msg: '登录失败，请稍后再试' }
      }
    },

    /**
     * 设置用户信息
     * @param {Object} userInfo - 用户信息
     */
    setUserInfo(userInfo) {
      this.token = userInfo.token
      this.nickname = userInfo.nickname || ''
      this.profilePicture = userInfo.profilePicture || null
      this.category = userInfo.category || null
      this.dealerId = userInfo.dealerId || ''
      this.dealer = userInfo.dealer || ''
      this.adminId = userInfo.adminId || ''
      this.hasLogin = true
    },

    /**
     * 清除用户信息（退出登录）
     */
    logout() {
      this.token = ''
      this.nickname = ''
      this.profilePicture = null
      this.category = null
      this.dealerId = ''
      this.dealer = ''
      this.adminId = ''
      this.hasLogin = false
      const menuStore = useMenuStore()
      menuStore.clearMenuData()
    },
  },

  persist: {
    key: 'user-info',
    storage: sessionStorage,
    paths: [
      'token',
      'nickname',
      'profilePicture',
      'category',
      'dealerId',
      'dealer',
      'adminId',
      'hasLogin',
    ],
  },
})
